package com.lianqi.emcpframework.logging.event;

import com.alibaba.fastjson.JSON;
import com.lianqi.emcpframework.logging.annotation.InvokingLogger;
import com.lianqi.emcpframework.logging.annotation.InvokingLoggerLevel;
import com.lianqi.emcpframework.logging.context.InvokingLoggerContext;
import com.lianqi.emcpframework.logging.level.strategy.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @program emcp-framework
 * @ClassName DefaultInvokingLoggerListener
 * @description: 缺省的日志监听
 * @author: sky
 * @create: 2018/11/18 15:05
 */
@Slf4j
public class DefaultInvokingLoggerListener implements InvokingLoggerListener {

    public static Map<InvokingLoggerLevel, LogLevelStrategy> strategyMap;

    static {
        strategyMap = new HashMap<>();
        strategyMap.put(InvokingLoggerLevel.OFF, new OffLogStrategy());
        strategyMap.put(InvokingLoggerLevel.ERROR, new ErrorLogStrategy());
        strategyMap.put(InvokingLoggerLevel.INFO, new InfoLogStrategy());
        strategyMap.put(InvokingLoggerLevel.DEBUG, new DebugLogStrategy());
        strategyMap.put(InvokingLoggerLevel.ALL, new AllLogStrategy());
    }

    @Override
    public void onlogging(InvokingLoggerContext loggerContext) {
        Method method = loggerContext.getMethod();
        InvokingLogger ann = AnnotationUtils.getAnnotation(method, InvokingLogger.class);
        LogLevelStrategy levelStrategy = strategyMap.get(ann.level());
        if (levelStrategy == null) {
            levelStrategy = getDefaultStrategy();
        }

        log.info(JSON.toJSONString(levelStrategy.parse(loggerContext)));
    }

    private LogLevelStrategy getDefaultStrategy() {
        return new InfoLogStrategy();
    }
}
